package com.dj.mingkong.admin.biz.repository.database.music;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dj.mingkong.common.enums.StatusEnum;
import com.dj.mingkong.common.infrastructure.base.dto.query.QueryVo;
import com.dj.mingkong.common.infrastructure.base.eo.BaseEo;
import com.dj.mingkong.common.infrastructure.base.repository.BaseDatabaseRepository;
import com.dj.mingkong.admin.biz.repository.database.music.mapper.TypeMapper;
import com.dj.mingkong.common.infrastructure.eo.database.music.TypeEo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 音乐类型repository
 *
 * @author zenglonghui
 * @date: 2022/5/18 10:08
 */
@Repository
public class TypeRepository extends BaseDatabaseRepository<TypeMapper, TypeEo, QueryVo> {
    @Override
    public Wrapper<TypeEo> buildQuery(TypeEo typeEo) {
        if (typeEo == null) {
            return null;
        }
        LambdaQueryWrapper<TypeEo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(typeEo.getId() != null, TypeEo::getId, typeEo.getId());
        queryWrapper.eq(typeEo.getParentId() != null, TypeEo::getParentId, typeEo.getParentId());
        queryWrapper.likeRight(StringUtils.isNotBlank(typeEo.getName()), TypeEo::getName, typeEo.getName());
        queryWrapper.eq(typeEo.getStatus() != null, TypeEo::getStatus, typeEo.getStatus());
        queryWrapper.likeRight(StringUtils.isNotBlank(typeEo.getDescription()), TypeEo::getDescription, typeEo.getDescription());
        queryWrapper.orderByDesc(TypeEo::getCreateTime);
        return queryWrapper;
    }

    public boolean existByParentIdAndName(Long parentId, String name) {
        return lambdaQuery().eq(TypeEo::getParentId, parentId)
                .eq(TypeEo::getName, name).exists();
    }

    public List<TypeEo> listByParentId(Long parentId) {
        return lambdaQuery()
                .eq(TypeEo::getParentId, parentId).orderByAsc(TypeEo::getSort).list();
    }

    public int countByIds(List<Long> ids) {
        return Math.toIntExact(lambdaQuery()
                .in(BaseEo::getId, ids)
                .eq(TypeEo::getStatus, StatusEnum.VALID.getIntVal())
                .count());
    }
}
